<template>
    <div class="main">
        <div class="splitTitle" v-if="rightsButtons['generate'] || rightsButtons['exportUnPostDetail'] || rightsButtons['importUnPostDetail']">
            <el-form :inline="true" :model="editBiltForm" class="demo-form-inline">
                <el-form-item label="账期" v-if="rightsButtons['generate']">
                    <el-date-picker v-model="editBiltForm.time" type="month" placeholder="选择日期" format="yyyy 年 MM 月"
                                    value-format="yyyy-MM-dd" style="width:auto">>
                    </el-date-picker>
                    <el-button type="primary" @click="createBil" :loading="btnLoading" plain>生成对账单</el-button>
                </el-form-item>
                <el-form-item label="选择商家" v-if="rightsButtons['exportUnPostDetail'] || rightsButtons['importUnPostDetail']">
                    <el-select v-model="merchant" filterable remote reserve-keyword placeholder="请输入关键词"
                               :remote-method="remoteMethod" :loading="Selloading" @change="onChangeEvent">
                        <el-option v-for="item in options4" :key="item.id" :label="item.merchantName" :value="item.id">
                        </el-option>
                    </el-select>

                    <el-button v-if="rightsButtons['exportUnPostDetail']" @click="exportBil()">导出商家未发送单明细</el-button>
                    <el-button v-if="rightsButtons['importUnPostDetail']" @click="importBil()">导入商家未发送单明细</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="splitTitle">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="商家名称：">
                    <el-input v-model="searchForm.merchantName" placeholder="商家名称" style="width:auto"></el-input>
                </el-form-item>
                <el-form-item label="账单日期：" style="width:auto">
                    <el-date-picker
                      v-model="dataPicker"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSubmit" size="medium">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <section>
            <!-- 数据列表 -->
            <div style="text-align:right;margin-bottom:20px;">
                <el-button v-if="rightsButtons['exportBill']" @click="exportBill" size="mini">导出账单</el-button>
                <el-button v-if="rightsButtons['publicBill']" @click="releaseBil" size="mini">发布账单</el-button>
                <el-button v-if="rightsButtons['cancelPublic']" @click="cancelReleaseBil" size="mini">取消发布账单</el-button>
            </div>

            <el-table :data="list" style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange" v-loading="loading">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column label="商家名称" width="180">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.merchantName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="账期" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.periodTime}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="推送商家时间" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.pushMerchantTime}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="发货金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.sendAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="退款金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.returnAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="汇总调整金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.billAdjustAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="明细调整金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.adjustAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="应付金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.finalAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" v-if="rightsButtons['modifyMoney'] || rightsButtons['view'] || rightsButtons['export']">
                    <template slot-scope="scope">
                        <el-button v-if="rightsButtons['modifyMoney']" size="mini" @click="handleEdit(scope.$index, scope.row)">
                            修改财务调整金额
                        </el-button>
                        <el-button v-if="rightsButtons['detail']" size="mini" @click="viewDetails(scope.$index, scope.row)">
                            查看
                        </el-button>
                        <el-button v-if="rightsButtons['export']" size="mini" @click="exportSingle(scope.$index, scope.row)">
                            导出
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                    background
                    @current-change="handleCurrentChange"
                    :current-page.sync="searchForm.pageNum"
                    :page-size="searchForm.pageSize"
                    layout="total, prev, pager, next"
                    :total="pageTotal">
            </el-pagination>
        </section>
        <el-dialog title="发布账单" :visible.sync="releaseBils" width="150%">
            <div class="dialogForm">
                <el-form :model="dialogForm" ref="dialogForm" :rules="release" label-width="90px" label-position="left">
                    <el-form-item label="发布时间：" prop="pushMerchantTime" label-width="130px">
                        <el-date-picker
                                v-model="dialogForm.pushMerchantTime"
                                type="date"
                                format="yyyy 年 MM 月 dd 日"
                                value-format="yyyy-MM-dd"
                                style="width:auto">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
            </div>
            <el-table :data="list2" style="width: 100%">
                <el-table-column label="商家名称" width="180">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.merchantName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="账期" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.periodTime}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="财务发货明细调整金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.adjustAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="汇总调整金额" width="180">
                    <template slot-scope="scope">
                        <span v-if="scope.row.billAdjustAmount"> {{ scope.row.billAdjustAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="推送商家时间" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.pushMerchantTime}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="发货金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.sendAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="退款金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.returnAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="应付金额" width="180">
                    <template slot-scope="scope">
                        <span> {{ scope.row.finalAmount}}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div class="footPrice">
                <span>汇总金额:{{totalPrice}}</span>
            </div>
            <span slot="footer">
            <el-button @click=" releaseBils = false">取 消</el-button>
            <el-button type="primary" @click="comfirmRelease()">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog title="导入送单明细" :visible.sync="bilWinbill" width="40%">
            <el-upload
                    class="upload-demo"
                    :action="upladUrl"
                    :limit="1"
                    accept='xls,xlsx'
                    :on-success="handleExceed"
                    :before-upload="fileCheck"
                    :multiple="false"
                    :file-list="fileList"
                    ref="upload">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xls,xlsx文件</div>
            </el-upload>
            <span slot="footer">
        <el-button type="primary" @click=" bilWinbill= false">确 定</el-button>
      </span>
        </el-dialog>
        <!-- 修改金额允许为负数 -->
        <el-dialog title="修改财务调整金额" :visible.sync="editingMoney" width="30%">
            <el-input-number v-model="money" label="金额" placehoder="请输入调整金额"></el-input-number>
            <div slot="footer">
                <el-button @click=" editingMoney= false">取 消</el-button>
                <el-button type="primary" @click="comfirmChangeMoney()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  export default {
    name: "bill",
    data() {
      return {
        totalPrice: 0,
        releaseBils: false,
        money: 0,
        fileList: [],
        currentId: 0,
        bilWinbill: false,
        editingMoney: false,
        currentCheck: "",
        options4: [],
        loading: true,
        Selloading: false,
        merchant: "",
        searchForm: {
          // merchantName: '',
          // startTime: '',
          // endTime: '',
          pageSize: 10,
          pageNum: 1
        },
        dataPicker: null,
        editBiltForm: {
          time: ""
        },
        list: [],
        pageTotal: 0,
        value6: null,

        multipleTable: [],
        dialogForm: {
          pushMerchantTime: null //发布时间
        },
        list2: [],
        release: {
          pushMerchantTime: {required: true, message: '请选择日期', trigger: 'blur'}
        },

        btnLoading: false
      };
    },
    mounted() {
      this.getData();
    },
    methods: {
      getData() {
        if (this.dataPicker) {
          this.searchForm.startTime = this.dataPicker[0];
          this.searchForm.endTime = this.dataPicker[1];
        } else {
          this.searchForm.startTime = '';
          this.searchForm.endTime = ''
        }
        this.request({
          url: "/finance/bill/list",
          method: "post",
          data: this.searchForm
        }).then(res => {
          if (res.status == 200) {
            this.list = res.data.rows;
            this.pageTotal = res.data.total;
          }
          this.loading = false;
        });
      },
      exportBill() {
        this.loading = true
        this.request({
          url: "/finance/bill/exportBill",
          method: "post",
          data: this.searchForm,
          responseType: 'blob',
          headers: {
            authorKey: 'billExportBill'
          }
        }).then(res => {
          this.loading = false
          this.downloadFile(res, '帐单列表.xls')
          // this.$message(res.msg || res.message)
        }).catch(e => {
          console.log(e)
          this.loading = false
        })
      },
      releaseBil() {
        this.totalPrice = 0;
        if (this.multipleTable.length < 1) {
          this.$message("请选择数据！");
        } else {
          this.releaseBils = true;
          document.getElementsByClassName('el-dialog')[0].style.maxWidth = 1000 + 'px';
          this.list2 = this.multipleTable;
        }
        for (let i = 0; i < this.multipleTable.length; i++) {
          this.totalPrice += this.multipleTable[i].finalAmount
        }
      },
      cancelReleaseBil() {
        if (this.multipleTable.length >= 1) {
          this.$confirm('此操作将取消账单的发布，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.request({
              url: "/finance/bill/cancelSendBill",
              method: "post",
              data: {data: this.multipleTable},
              headers: {
                authorKey: 'billCancelPublic'
              }
            }).then(res => {
              if (res.status == 200) {
                this.$message({
                  type: 'success',
                  message: '取消发布订单成功'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })

          })
        } else {
          this.$message('请先选择数据')
          return;
        }
      },
      onSubmit() {
        this.searchForm.pageNum = 1;
        this.getData();

      },
      handleEdit(index, row) {
        this.editingMoney = true;
        this.money = row.billAdjustAmount;
        this.currentId = row.id;
      },
      handleCurrentChange(val) {
        this.searchForm.pageNum = val;
        this.getData();
      },
      comfirmChangeMoney(money) {
        this.request({
          url: "/finance/bill/update",
          method: "post",
          data: {
            data: {
              id: this.currentId,
              adjustAmount: this.money
            }
          },
          headers: {
            authorKey: 'billModifyMoney'
          }
        }).then(res => {
          if (res.status == 200) {
            this.$message({
              type: "success",
              message: "修改成功"
            });
          } else {
            this.$message({
              type: "error",
              message: res.message
            });
          }
          this.editingMoney = false;
          this.getData()
        });

      },
      handleSelectionChange(val) {
        this.multipleTable = val;
      },
      comfirmRelease() {

        this.multipleTable.forEach((item, index) => {
          this.multipleTable[
            index
            ].pushMerchantTime = this.dialogForm.pushMerchantTime;
        });
        if (this.dialogForm.pushMerchantTime) {
          this.request({
            url: "/finance/bill/sendBill",
            method: "post",
            data: {data: this.multipleTable},
            headers: {
              authorKey: 'billPublicBill'
            }
          }).then(res => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "操作成功"
              });
            } else {
              this.$message({
                type: "error",
                message: res.message
              });
            }
            this.releaseBils = false;
          });
        } else {
          this.$message("请选择日期")
        }

      },
      remoteMethod(val) {
        //远程搜索关键字
        this.Selloading = true;
        this.request({
          url: "/finance/merchant/list",
          method: "post",
          data: {
            data: {
              pageNum: 1,
              pageSize: 100,
              merchantName: val
            },

          }
        }).then(res => {
          if (res.status == 200) {
            this.options4 = res.data.rows;
            setTimeout(() => {
              this.Selloading = false;
            }, 500);
          } else {
            this.$message({
              type: "error",
              message: res.message
            });
          }
        });
      },
      createBil() {
        if (this.editBiltForm.time == "") {
          this.$message({
            type: "error",
            message: "请选择账期"
          });
          return;
        } else {
          this.btnLoading = true
          this.request({
            url: "/finance/bill/generateBills",
            method: "post",
            data: {
              data: {periodTime: this.editBiltForm.time}
            },
            headers: {
              authorKey: 'billGenerate'
            }
          }).then(res => {
            this.$message({
              type: "success",
              message: "生成账单成功！"
            });
            this.btnLoading = false
          }).catch(e => {
            this.btnLoading = false
          });

        }
      },
      exportSingle(row, index) {   //导出单条数据
        this.request({
          url: "/finance/billDetail/exportBillDetail",
          method: "post",
          data: {
            data: index
          },
          responseType: 'arraybuffer',
          headers: {
            authorKey: 'billExportBill'
          }
        }).then(res => {
          this.downloadFile(res)

        });
      },
      exportBil() {
        //导出账单明细
        if (this.currentCheck !== "") {
          this.request({
            url: "/finance/billDetail/exportNoSendBillDetail",
            method: "post",
            data: {
              data: [{
                merchantId: this.currentCheck
              }]
            },
            headers: {
              authorKey: 'billExportUnPostDetail'
            },
            responseType: 'arraybuffer'
          }).then(res => {
            this.downloadFile(res)
          });
        } else {
          this.$message('请先选择商家');
          return false;
        }
      },
      importBil() {
        this.bilWinbill = true;
      },
      onChangeEvent(val) {
        this.currentCheck = val;
      },
      handleExceed(res, file, fileList) {
        this.request({
          url: "/finance/billDetail/importNoSendBillDetail",
          method: "post",
          data: {
            data: res.filePath
          },
          headers: {
            authorKey: 'billImportUnPostDetail'
          }
        }).then(res => {
          if (res.status == 200) {
            this.startCircleChecking(res.data[0])
          } else {
            this.$message({
              type: "error",
              message: res.sysMsg
            });
            return false;
          }
        })
        this.bilWinbill = false;
        this.$refs.upload.clearFiles()
        this.fileList = []
      },
      viewDetails(index, row) {
        this.$router.push({
          name: "billDetail",
          params: {
            id: row.id
          }
        });
      },
      fileCheck(file) {
        if (file.name.indexOf('xls') <= -1) {
          this.$message('只能上传xls、xlsx格式文件')
          return false;
        }
      },
      startCircleChecking(code) {
        let codes = code;
        this.request({
          url: '/finance/bill/getLastOne?codes=' + code,
          method: 'get'
        }).then(res => {
          console.log(res.data.status)
          if (res.data.status !== 1) {
            setTimeout(() => {
              this.startCircleChecking(codes)
            }, 1000)
          } else {
            this.$notify({
              type: res.data.type ? 'success' : 'error',
              title: '提示',
              message: res.data.description
            });
          }
        })
      }
    }
  };
</script>
<style scoped>
    .splitTitle {
        display: block;
        width: 100%;
        margin: 15px 0;
        background-color: white;
        padding: 10px;
    }

    .dialogForm {
        margin: 20px;
    }

    .footPrice {
        text-align: right;
        margin-top: 20px;
        padding-right: 10px;
    }

    .el-input-number .el-dialog .el-input--medium {
        width: auto !important;
    }
</style>
